package 代码随想录.回溯.电话号码的字母组合;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LeetCode17 {
    //使用全局变量可以在递归的时候少传入一个参数
    List<String> combinations = new ArrayList<>();

    public List<String> letterCombinations(String digits) {
        if (digits.length() == 0) {
            return combinations;
        }
        Map<Character, String> phoneMap = new HashMap<Character, String>() {
            {
                put('2', "abc");
                put('3', "def");
                put('4', "ghi");
                put('5', "jkl");
                put('6', "mno");
                put('7', "pqrs");
                put('8', "tuv");
                put('9', "wxyz");
            }
        };
        backTrack(phoneMap, digits, 0, new StringBuffer());

        return combinations;
    }

    //combination是维护的字符串，表示已有的字符序列
    public void backTrack(Map<Character, String> phoneMap, String digits, int index, StringBuffer combination) {
        if (index == digits.length()) {
            combinations.add(combination.toString());
        } else {
            char digit = digits.charAt(index);
            String letters = phoneMap.get(digit);//获取该数字对应的字母
            int letterCount = letters.length();
            for (int i = 0; i < letterCount; i++) {
                combination.append(letters.charAt(i));  //取一个字母拼接到combination
                backTrack(phoneMap, digits, index + 1, combination);
                combination.deleteCharAt(index);//回溯，不取当前字母
            }
        }
    }

    public static void main(String[] args) {
        LeetCode17 code = new LeetCode17();
        System.out.println(code.letterCombinations("23"));
    }
}
